package com.quanyan.place.wrapper.impl;

import com.alibaba.rocketmq.common.message.MessageExt;
import com.google.gson.Gson;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.orderpay.response.mq.OrderCallBackMsg;
import com.quanyan.orderpay.response.mq.OrderNotifyMsg;
import com.quanyan.orderpay.response.mq.RefundNotifyMsg;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.place.component.MqPlaceOrderProducerClientImpl;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.apireq.ReqOrderOperate;
import com.quanyan.place.wrapper.MqConsumerWrapper;
import com.quanyan.place.wrapper.PlaceOrderServiceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Kingson.chan on 2016/6/24 0024.
 */
@Service("mqConsumerWrapperImpl")
public class MqConsumerWrapperImpl implements MqConsumerWrapper {
    private static final Logger log = LoggerFactory.getLogger(MqConsumerWrapperImpl.class);
    @Autowired
    PlaceOrderServiceWrapper placeOrderServiceWrapper;

    @Autowired
    private MqPlaceOrderProducerClientImpl placeOrderProducerClientImpl;

    @Override
    public APIResponse<?> orderPayOperate(MessageExt messageExt) {
        //String key = messageExt.getKeys();  //订单号
        String msgId = messageExt.getMsgId();
        byte[] bodyByte = messageExt.getBody();
        OrderNotifyMsg orderNotifyMsg = (OrderNotifyMsg) ObjectUtil.toObject(bodyByte);
        //log.warn(Thread.currentThread().getName()+ " msgId:" + msgId + " receive messages: "+ JSON.toJSONString(orderNotifyMsg) );
        //支付成功处理
        if(OrderNotifyMsg.RESULT_CODE_USER_PAY_SUCCESS.equals(orderNotifyMsg.getResultCode())){
            ReqOrderOperate reqOrderOperatePaySuccess = new ReqOrderOperate();
            reqOrderOperatePaySuccess.setUid(orderNotifyMsg.getUid());
            reqOrderOperatePaySuccess.setOrderNo(orderNotifyMsg.getOutTradeNo());
            reqOrderOperatePaySuccess.setOperateType(PlaceConstants.ORDER_COMPLETE_OPERATE);
            reqOrderOperatePaySuccess.setUserType(PlaceConstants.ORDER_OPERATE_ADMINUSER);
            reqOrderOperatePaySuccess.setOrderOperateKey(PlaceConstants.ORDER_OPERATE_KEY);
            APIResponse apiResponse =  placeOrderServiceWrapper.orderOperate(reqOrderOperatePaySuccess);
            //设置mq生产者消息体
            OrderCallBackMsg orderCallBackMsg = new OrderCallBackMsg();
            orderCallBackMsg.setOrderNo(orderNotifyMsg.getOrderNo());
            orderCallBackMsg.setType(OrderCallBackMsg.PAY);
            if(apiResponse.isRet()){
                orderCallBackMsg.setState(OrderCallBackMsg.SUCCESS);
                log.warn("mq消息:订单支付成功，msgId：{} 用户号：{}，订单号：{} ", msgId, orderNotifyMsg.getUid(), orderNotifyMsg.getOutTradeNo());
            }
            else {
                orderCallBackMsg.setState(OrderCallBackMsg.FAIL);
                log.warn("mq消息:订单支付失败，msgId：{} 用户号：{}，订单号：{} ", msgId, orderNotifyMsg.getUid(), orderNotifyMsg.getOutTradeNo());
            }
            //mq通过发送消息通知订单系统支付成功
            feedbackOrderSystemOrderStatus(orderCallBackMsg);
            return apiResponse;
        }
        else if(OrderNotifyMsg.RESULT_CODE_USER_PAY_FAIL.equals(orderNotifyMsg.getResultCode())){
            //支付失败，进行取消订单处理
            ReqOrderOperate reqOrderOperatePayFail = new ReqOrderOperate();
            reqOrderOperatePayFail.setUid(orderNotifyMsg.getUid());
            reqOrderOperatePayFail.setOrderNo(orderNotifyMsg.getOutTradeNo());
            reqOrderOperatePayFail.setOperateType(PlaceConstants.ORDER_CANCEL_OPERATE);
            reqOrderOperatePayFail.setUserType(PlaceConstants.ORDER_OPERATE_ADMINUSER);//admin用户对于取消次数不做限制
            reqOrderOperatePayFail.setOrderOperateKey(PlaceConstants.ORDER_OPERATE_KEY);
            APIResponse apiResponse =  placeOrderServiceWrapper.orderOperate(reqOrderOperatePayFail);
            //设置mq生产者消息体
            OrderCallBackMsg orderCallBackMsg = new OrderCallBackMsg();
            orderCallBackMsg.setOrderNo(orderNotifyMsg.getOrderNo());
            orderCallBackMsg.setType(OrderCallBackMsg.CLOSE);
            if(apiResponse.isRet()){
                orderCallBackMsg.setState(OrderCallBackMsg.SUCCESS);
                log.warn("mq消息:订单支付失败处理成功，msgId：{} 用户号：{}，订单号：{} ", msgId, orderNotifyMsg.getUid(), orderNotifyMsg.getOutTradeNo());
            }
            else {
                orderCallBackMsg.setState(OrderCallBackMsg.FAIL);
                log.warn("mq消息:订单支付失败处理失败，msgId：{} 用户号：{}，订单号：{} ", msgId, orderNotifyMsg.getUid(), orderNotifyMsg.getOutTradeNo());
            }
            //mq通过发送消息通知订单系统支付成功
            feedbackOrderSystemOrderStatus(orderCallBackMsg);
            return apiResponse;
        }

        return APIResponse.returnFail("");
    }

    @Override
    public APIResponse<?> orderRefundOperate(MessageExt messageExt) {
        String msgId = messageExt.getMsgId();
        byte[] bodyByte = messageExt.getBody();
        RefundNotifyMsg refundNotifyMsg = (RefundNotifyMsg) ObjectUtil.toObject(bodyByte);
        //log.warn(Thread.currentThread().getName()+ " msgId:" + msgId + " receive messages: "+ JSON.toJSONString(orderNotifyMsg) );
        if(RefundStatusEnum.SUCCESS.getId() == refundNotifyMsg.getRefundState()){
            ReqOrderOperate reqOrderOperatePayRefundSuccess = new ReqOrderOperate();
            reqOrderOperatePayRefundSuccess.setUid(refundNotifyMsg.getUid());
            reqOrderOperatePayRefundSuccess.setOrderNo(refundNotifyMsg.getOutTradeNo());
            reqOrderOperatePayRefundSuccess.setOperateType(PlaceConstants.ORDER_COMPLETE_UNSUBSCRIBE_OPERATE);
            reqOrderOperatePayRefundSuccess.setUserType(PlaceConstants.ORDER_OPERATE_ADMINUSER);
            reqOrderOperatePayRefundSuccess.setOrderOperateKey(PlaceConstants.ORDER_OPERATE_KEY);
            reqOrderOperatePayRefundSuccess.setExceptionFlag(refundNotifyMsg.getExceptionFlag());
            APIResponse apiResponse =  placeOrderServiceWrapper.orderOperate(reqOrderOperatePayRefundSuccess);
            //设置mq生产者消息体
            OrderCallBackMsg orderCallBackMsg = new OrderCallBackMsg();
            orderCallBackMsg.setOrderNo(refundNotifyMsg.getOrderNo());
            orderCallBackMsg.setType(OrderCallBackMsg.REFUND);
            if(apiResponse.isRet()){
                orderCallBackMsg.setState(OrderCallBackMsg.SUCCESS);
                log.warn("mq消息:订单退款成功，msgId：{} ，用户号：{}，订单号：{} ", msgId, refundNotifyMsg.getUid(), refundNotifyMsg.getOutTradeNo());
            } else {
                orderCallBackMsg.setState(OrderCallBackMsg.FAIL);
                log.warn("mq消息:订单退款失败，msgId：{} ，用户号：{}，订单号：{} ", msgId, refundNotifyMsg.getUid(), refundNotifyMsg.getOutTradeNo());
            }
            //mq通过发送消息通知订单系统支付成功
            feedbackOrderSystemOrderStatus(orderCallBackMsg);
            return apiResponse;
        }
        //其他状态暂时不做处理
        else if(RefundStatusEnum.FAIL.getId() == refundNotifyMsg.getRefundState()){
            log.warn("mq消息:订单退款失败，msgId：{} ，用户号：{}，订单号：{} ",msgId ,refundNotifyMsg.getUid(), refundNotifyMsg.getOutTradeNo());
        }
        else if (RefundStatusEnum.CHANGE.getId() == refundNotifyMsg.getRefundState()){
            log.warn("mq消息:订单退款失败,需要人工退款，msgId：{} ，用户号：{}，订单号：{} ", msgId, refundNotifyMsg.getUid(), refundNotifyMsg.getOutTradeNo());
        }
        else {
            log.warn("mq消息:订单退款异常，msgId：{} ，用户号：{}，订单号：{} 退款状态：{}",msgId , refundNotifyMsg.getUid(), refundNotifyMsg.getOutTradeNo(),refundNotifyMsg.getRefundState());
        }
        return APIResponse.returnFail("");

    }


    @Override
    public APIResponse<?> orderCancleToUnsubscribeOperate(MessageExt messageExt) {
        String msgId = messageExt.getMsgId();
        byte[] bodyByte = messageExt.getBody();
        RefundNotifyMsg refundNotifyMsg = (RefundNotifyMsg) ObjectUtil.toObject(bodyByte);
        ReqOrderOperate reqOrderOperatePayRefundSuccess = new ReqOrderOperate();
        reqOrderOperatePayRefundSuccess.setUid(refundNotifyMsg.getUid());
        reqOrderOperatePayRefundSuccess.setOrderNo(refundNotifyMsg.getOutTradeNo());
        reqOrderOperatePayRefundSuccess.setOperateType(PlaceConstants.ORDER_CANCEL_TO_UNSUBSCRIBE_OPERATE);
        reqOrderOperatePayRefundSuccess.setUserType(PlaceConstants.ORDER_OPERATE_ADMINUSER);
        reqOrderOperatePayRefundSuccess.setOrderOperateKey(PlaceConstants.ORDER_OPERATE_KEY);
        APIResponse apiResponse =  placeOrderServiceWrapper.orderOperate(reqOrderOperatePayRefundSuccess);
        //设置mq生产者消息体
        OrderCallBackMsg orderCallBackMsg = new OrderCallBackMsg();
        orderCallBackMsg.setOrderNo(refundNotifyMsg.getOrderNo());
        orderCallBackMsg.setType(OrderCallBackMsg.REFUND_SUBMIT);
        if(apiResponse.isRet()){
            orderCallBackMsg.setState(OrderCallBackMsg.SUCCESS);
            log.warn("mq消息:订单取消转退款成功，msgId：{} ，用户号：{}，订单号：{} ", msgId, refundNotifyMsg.getUid(), refundNotifyMsg.getOutTradeNo());
        } else {
            orderCallBackMsg.setState(OrderCallBackMsg.FAIL);
            log.warn("mq消息:订单取消转退款失败，msgId：{} ，用户号：{}，订单号：{} ", msgId, refundNotifyMsg.getUid(), refundNotifyMsg.getOutTradeNo());
        }
        //mq通过发送消息通知订单系统支付成功
        feedbackOrderSystemOrderStatus(orderCallBackMsg);
        return apiResponse;

    }

    @Override
    public APIResponse<?> orderCancleOperate(MessageExt messageExt) {
        String msgId = messageExt.getMsgId();
        byte[] bodyByte = messageExt.getBody();
        OrderNotifyMsg orderNotifyMsg = (OrderNotifyMsg) ObjectUtil.toObject(bodyByte);
        ReqOrderOperate reqOrderOperateClose = new ReqOrderOperate();
        reqOrderOperateClose.setUid(orderNotifyMsg.getUid());
        reqOrderOperateClose.setOrderNo(orderNotifyMsg.getOutTradeNo());
        reqOrderOperateClose.setOperateType(PlaceConstants.ORDER_CANCEL_OPERATE);
        reqOrderOperateClose.setUserType(PlaceConstants.ORDER_OPERATE_ADMINUSER);//admin用户对于取消次数不做限制
        reqOrderOperateClose.setOrderOperateKey(PlaceConstants.ORDER_OPERATE_KEY);
        reqOrderOperateClose.setIsCallBackOrder(PlaceConstants.NO);//不通知订单系统
        APIResponse apiResponse =  placeOrderServiceWrapper.orderOperate(reqOrderOperateClose);
        //设置mq生产者消息体
        OrderCallBackMsg orderCallBackMsg = new OrderCallBackMsg();
        orderCallBackMsg.setOrderNo(orderNotifyMsg.getOrderNo());
        orderCallBackMsg.setType(OrderCallBackMsg.CLOSE);
        if(apiResponse.isRet()){
            orderCallBackMsg.setState(OrderCallBackMsg.SUCCESS);
            log.warn("mq消息:订单关闭处理成功，msgId：{} 用户号：{}，订单号：{} ", msgId, orderNotifyMsg.getUid(), orderNotifyMsg.getOutTradeNo());
        }
        else {
            orderCallBackMsg.setState(OrderCallBackMsg.FAIL);
            log.warn("mq消息:订单关闭处理失败，msgId：{} 用户号：{}，订单号：{} ", msgId, orderNotifyMsg.getUid(), orderNotifyMsg.getOutTradeNo());
        }
        //mq通过发送消息通知订单系统支付成功
        feedbackOrderSystemOrderStatus(orderCallBackMsg);
        return apiResponse;
    }

    private void feedbackOrderSystemOrderStatus(OrderCallBackMsg orderCallBackMsg) {
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setTopic(OrderPayService.TOPIC_ORDER_CALLBACK_NOTIFY);
        mqRequestMsg.setTag(Constants.ORDER_SYSTEM_CODE);
        mqRequestMsg.setMsgId(orderCallBackMsg.getOrderNo()); //订单号
        mqRequestMsg.setFlag(0);
        mqRequestMsg.setBody(ObjectUtil.toByteArray(orderCallBackMsg));
        log.warn("SEND TO MQ BODY : DATA : {}", new Gson().toJson(orderCallBackMsg).toString());
        placeOrderProducerClientImpl.asyncSend(mqRequestMsg);
    }
}
